import type { NextApiResponse } from 'next';
import * as categoryService from '@/common/service/g_category';
import R from '@common/type/response';
import { AuthenticatedRequest, withAuth } from '@common/middleware/auth';

// 构建树形结构
function buildTree(list: any[]) {
  const map: Record<number, any> = {};
  const roots: any[] = [];
  
  // 创建节点映射
  list.forEach(item => {
    map[item.id] = { 
      ...item, 
      children: [],
      label: item.alias,
      value: item.alias,
      disabled: item.status === 0,
      title: item.alias // TreeSelect需要title字段
    };
  });
  
  // 构建父子关系
  list.forEach(item => {
    if (item.fid && map[item.fid]) {
      map[item.fid].children.push(map[item.id]);
    } else {
      roots.push(map[item.id]);
    }
  });
  return roots;
}

export async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
  if (req.method === 'GET') {
    try {
      const { list } = await categoryService.getCategoryList({}, 0, 1000); // 获取所有分类
      const treeData = buildTree(list);
      R.success(res, treeData);
    } catch (error: any) {
      console.error('获取分类选项错误:', error);
      R.error(res, error.message || '获取分类选项失败');
    }
  } else {
    R.error(res, 'Method Not Allowed');
  }
}

export default withAuth(handler); 